package com.xm.share.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xm.share.common.config.Constants;
import com.xm.share.common.config.SystemConfig;
import com.xm.share.common.utils.MD5Util;
import com.xm.share.common.utils.MessageModel;
import com.xm.share.common.utils.ResponseEntity;
import com.xm.share.model.Comment;
import com.xm.share.model.PictureFile;
import com.xm.share.model.Pictureshare;
import com.xm.share.model.UserInfo;
import com.xm.share.model.vo.PictureShareDetailDto;
import com.xm.share.model.vo.PictureShareRequest;
import com.xm.share.model.vo.SystemReportDto;
import com.xm.share.model.vo.UserInfoDto;
import com.xm.share.service.CommentService;
import com.xm.share.service.PictureFileService;
import com.xm.share.service.PictureShareService;
import com.xm.share.service.UserService;

@Controller
public class UserController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private PictureShareService pictureShareService;

	@Autowired
	private CommentService commentService;

	@Autowired
	private PictureFileService pictureFileService;

	/**
	 * 图片类型
	 */
	private String type = "'image/jpg','image/gif','image/png','image/bmp','image/pjpeg','image/jpeg'";

	/**
	 * 首页
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request) {
		// UserInfo user = getCurrentUser(request.getSession());
		// if (user == null) {
		// return "login";
		// } else {
		// String authority = user.getGrantedAuthority();
		// if ("administrator".equals(authority)) {
		// return "admin_index";
		// } else {
		return "login";
		// }
		// }
	}

	/**
	 * 登出
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute(Constants.CURRENT_USER);
		session.removeAttribute(Constants.USER_NAME);
		session.removeAttribute(Constants.USER_ID);
		session.invalidate();
		return "login";
	}

	@RequestMapping(value = "toRegister", method = RequestMethod.GET)
	public String register() {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public MessageModel register(String password, String email, String grantedAuthority, HttpServletRequest request)
			throws Exception {
		password = StringUtils.trimAllWhitespace(password);
		email = StringUtils.trimAllWhitespace(email);
		String userName = email;
		String guid = UUID.randomUUID().toString();

		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(email);
		userInfo.setGuid(guid);
		userInfo.setPassword(MD5Util.string2MD5(password + guid));
		userInfo.setEmail(email);
		userInfo.setCreatedOn(new Date());
		userInfo.setGrantedAuthority(grantedAuthority);
		MessageModel messageModel = userService.register(userInfo);
		LOGGER.info("一个新用户注册成功，userName = {}", userName);
		if ("administrator".equals(grantedAuthority)) {
			HttpSession session = request.getSession();
			session.setAttribute(Constants.CURRENT_USER, userInfo);
		}
		return messageModel;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public MessageModel login(UserInfo userLoginPo, HttpServletRequest request) throws Exception {
		MessageModel model = new MessageModel(false);
		model.setMsg("请输入正确的用户名和密码");
		UserInfo userInfo = userService.findByName(userLoginPo.getUserName());
		if (userInfo != null) {
			// 密码加盐进行md5运算
			String passwordMD5 = MD5Util.string2MD5(userLoginPo.getPassword() + userInfo.getGuid());
			if (userInfo.getPassword().equals(passwordMD5)) {
				model.setSuccess(true);
				model.setMsg("登陆成功");
				Map<String, Object> data = new HashMap<>();
				data.put("id", userInfo.getId());
				data.put("name", userInfo.getUserName());
				HttpSession session = request.getSession();
				session.setAttribute(Constants.USER_NAME, userInfo.getUserName());
				session.setAttribute(Constants.USER_ID, userInfo.getId());
				session.setAttribute(Constants.CURRENT_USER, userInfo);
				session.setAttribute("anth", userInfo.getGrantedAuthority());
				if ("administrator".equals(userInfo.getGrantedAuthority())) {
					data.put("admin", true);
				} else {
					data.put("admin", false);
				}
				model.setObj(data);
			}
		}
		return model;
	}

	@RequestMapping(value = "/admin/sys_report")
	@ResponseBody
	public ResponseEntity<SystemReportDto> getSysReport(HttpServletRequest request) throws Exception {
		ResponseEntity<SystemReportDto> result = new ResponseEntity<>();
		UserInfo user = getCurrentUser(request.getSession());
		if (user == null) {
			result.setCode(401);
		} else {
			SystemReportDto systemReport = userService.getSystemReport();
			result.setResult(systemReport);
		}
		return result;
	}

	@RequestMapping(value = "/picture_share_list")
	@ResponseBody
	public ResponseEntity<List<PictureShareDetailDto>> getPictrureShareList(HttpServletRequest request)
			throws IOException {
		ResponseEntity<List<PictureShareDetailDto>> responseEntity = new ResponseEntity<List<PictureShareDetailDto>>(
				true);
		Assert.notNull(request.getParameter("pageNo"));
		Assert.notNull(request.getParameter("pageSize"));
		int pageNo = Integer.parseInt(request.getParameter("pageNo"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		List<PictureShareDetailDto> detailList = pictureShareService.getDetailList(pageNo, pageSize);
		responseEntity.setResult(detailList);
		return responseEntity;
	}

	/**
	 * 用户管理列表
	 *
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/user_info_list")
	@ResponseBody
	public ResponseEntity<List<UserInfoDto>> getUserInfoList(HttpServletRequest request) throws Exception {
		ResponseEntity<List<UserInfoDto>> responseEntity = new ResponseEntity<List<UserInfoDto>>(true);
		int pageNo = Integer.parseInt(request.getParameter("pageNo"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		List<UserInfoDto> userinfoDtoList = userService.getUserinfoDtoList(pageNo, pageSize);
		responseEntity.setResult(userinfoDtoList);
		return responseEntity;
	}

	@RequestMapping(value = "/delete_user/{userId}")
	@ResponseBody
	public String deleteUser(@PathVariable("userId") Long userId) throws Exception {
		userService.deleteUser(userId);
		return "true";
	}

	@RequestMapping(value = "/delete_Share/{id}")
	@ResponseBody
	public String deleteShare(@PathVariable("id") Long id) throws Exception {
		pictureShareService.deletePictureShare(id);
		return "true";
	}

	/**
	 * 置顶
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/makeTop/{id}")
	@ResponseBody
	public String makeTop(@PathVariable("id") Long id, HttpSession session) throws Exception {
		Long userId = getCurrentUserId(session);
		pictureShareService.makeTop(id, userId);
		return "true";
	}

	@RequestMapping(value = "/deleteTop/{id}")
	@ResponseBody
	public String deleteTop(@PathVariable("id") Long id, HttpSession session) throws Exception {
		Long userId = getCurrentUserId(session);
		pictureShareService.deleteTop(id, userId);
		return "true";
	}

	/**
	 * 实现jquery file upload上传文件。
	 *
	 * @param file
	 *            文件
	 * @param request
	 *            请求
	 */
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadImages(@RequestParam(value = "filesImage", required = false) MultipartFile file,
			HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
		// 验证图片上传格式
		String contentType = file.getContentType();
		LOGGER.error("上传图片格式为: {}", contentType);
		if (!type.contains(contentType)) {
			result.put("result", Boolean.FALSE.toString());
			result.put("msg", "图片格式不正确!");
			return result;
		}
		UserInfo userInfo = getCurrentUser(request.getSession());
		// 创建文件夹，保存用户头像
		String separator = File.separator;
		String path = SystemConfig.getUploadFilePath() + userInfo.getId() + separator;
		String fileName = file.getOriginalFilename();
		String newName = generatorNewName(fileName);
		File targetFile = new File(path, newName);
		targetFile.mkdirs();
		// 保存 文件
		try {
			file.transferTo(targetFile);
			UserInfo info = new UserInfo();
			info.setId(userInfo.getId());
			info.setPhotoUrl(targetFile.getPath());
			userService.updateUserInfo(info);
			result.put("result", Boolean.TRUE.toString());
			result.put("id", userInfo.getId());
		} catch (Exception e) {
			LOGGER.error("上传图片出错,", e);
		}
		return result;
	}

	/**
	 * 回显头像
	 */
	@RequestMapping(value = "/static/user/{userId}")
	@ResponseBody
	public org.springframework.http.ResponseEntity<byte[]> showHeadPhoto(@PathVariable("userId") Long userId,
			HttpServletRequest request) throws Exception {
		org.springframework.http.ResponseEntity<byte[]> responseEntity = showDefault(request);
		if (userId != null) {
			UserInfo userInfo = userService.findById(userId);
			if (userInfo != null) {
				String photoUrl = userInfo.getPhotoUrl();
				if (org.apache.commons.lang3.StringUtils.isNoneBlank(photoUrl)) {
					responseEntity = showImages(new File(photoUrl));
				}
			}
		}
		return responseEntity;
	}

	@RequestMapping(value = "/myavotar")
	@ResponseBody
	public org.springframework.http.ResponseEntity<byte[]> myavotar(HttpServletRequest request) throws Exception {
		UserInfo userInfo = getCurrentUser(request.getSession());
		if (userInfo != null) {
			String photoUrl = userInfo.getPhotoUrl();
			if (org.apache.commons.lang3.StringUtils.isNoneBlank(photoUrl)) {
				File file = new File(photoUrl);
				if (file.exists()) {
					return showImages(new File(photoUrl));
				} else {
					return showDefault(request);
				}
			}
		}
		return showDefault(request);
	}

	/**
	 * 新增一条图片分享消息
	 */
	@RequestMapping(value = "/picture_share", method = RequestMethod.POST)
	public ModelAndView uploadMessage(ModelAndView modelAndView, HttpServletRequest request,
			@RequestParam("pictures") MultipartFile[] pictures) throws Exception {
		UserInfo userInfo = getCurrentUser(request.getSession());
		String page = request.getParameter("page");
		List<PictureFile> pictureFileList = new ArrayList<PictureFile>();
		if (pictures != null && pictures.length > 0) {
			for (MultipartFile pic : pictures) {
				if (!pic.isEmpty()) {
					// 验证图片上传格式
					String contentType = pic.getContentType();
					LOGGER.error("上传图片格式为: {}", contentType);
					if (!type.contains(contentType)) {
						modelAndView.addObject("result", "图片格式不正确!");
						modelAndView.setViewName(page);
						return modelAndView;
					}
					PictureFile pictureFile = new PictureFile();
					String pictureName = generatorNewName(pic.getOriginalFilename());
					pic.transferTo(new File(SystemConfig.getUploadFilePath() + pictureName));
					pictureFile.setFileName(pictureName);
					pictureFile.setFileSize(Double.valueOf(pic.getSize() + ""));
					pictureFile.setFileType(pic.getContentType());
					pictureFile.setFileUrl("/" + pictureFile.getFileName());
					pictureFile.setUserid(userInfo.getId());
					pictureFileList.add(pictureFile);
				}
			}
		}

		Pictureshare pictureShare = new Pictureshare();
		pictureShare.setCreatedOn(new Date());
		pictureShare.setRemark(URLDecoder.decode(request.getParameter("remark"), "UTF-8"));
		pictureShare.setUserId(userInfo.getId());

		PictureShareRequest pictureShareRequest = new PictureShareRequest(pictureShare, pictureFileList);
		pictureShareService.addPictureShare(pictureShareRequest);
		if ("administrator".equals(userInfo.getGrantedAuthority())) {
			modelAndView.setViewName("success");
		} else {
			modelAndView.setViewName("all_share");
		}
		return modelAndView;
	}

	/**
	 * 增加评论
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/comment")
	@ResponseBody
	public String addComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo userInfo = getCurrentUser(request.getSession());
		Long pictureShareId = Long.parseLong(request.getParameter("pictureShareId"));
		String commentStr = URLDecoder.decode(request.getParameter("comment"), "UTF-8");
		Comment comment = new Comment();
		comment.setPictureShareId(pictureShareId);
		comment.setCreatedOn(new Date());
		comment.setComment(commentStr);
		comment.setCommentUseId(userInfo.getId());
		commentService.addComment(comment);
		return Boolean.TRUE.toString();
	}

	@RequestMapping(value = "updateAccount")
	@ResponseBody
	public String updateAccount(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo userInfo = getCurrentUser(request.getSession());
		userInfo.setPassword(
				MD5Util.string2MD5(URLDecoder.decode(request.getParameter("password"), "UTF-8") + userInfo.getGuid()));
		userInfo.setModifiedOn(new Date());
		userService.modifyUserInfo(userInfo);
		return Boolean.TRUE.toString();
	}

	@RequestMapping(value = "/search")
	@ResponseBody
	public ResponseEntity<List<PictureShareDetailDto>> search(HttpServletRequest request, String order)
			throws Exception {
		ResponseEntity<List<PictureShareDetailDto>> responseEntity = new ResponseEntity<List<PictureShareDetailDto>>(
				true);
		String condition = URLDecoder.decode(request.getParameter("condition"), "UTF-8");
		List<PictureShareDetailDto> pictureShareDetailDtos = pictureShareService.findPictureShare(condition, order);
		responseEntity.setResult(pictureShareDetailDtos);
		return responseEntity;
	}

	@RequestMapping(value = "/del_comment/{commentId}")
	@ResponseBody
	public String delComment(@PathVariable("commentId") Long commentId) throws Exception {
		commentService.delComment(commentId);
		return Boolean.TRUE.toString();
	}

	private String generatorNewName(String fileName) {
		String s = UUID.randomUUID().toString();
		int lastIndexOf = fileName.lastIndexOf(".");
		String suffix = fileName.substring(lastIndexOf, fileName.length());
		return s + suffix;
	}

	@RequestMapping(value = "/picture_share_detail")
	@ResponseBody
	public MessageModel getPictrureShareDetail(HttpServletRequest request) throws IOException {
		MessageModel model = new MessageModel(true);
		Long pictureShareId = Long.parseLong(request.getParameter("pictureShareId"));
		PictureShareDetailDto detail = pictureShareService.getDetail(pictureShareId);
		model.setObj(detail);
		return model;
	}

	@RequestMapping(value = "fileupload/{id}")
	public org.springframework.http.ResponseEntity<byte[]> downLoadFile(@PathVariable("id") Long id) throws Exception {
		PictureFile pictureFile = pictureFileService.findById(id);
		if (pictureFile != null) {
			String path = SystemConfig.getUploadFilePath() + pictureFile.getFileUrl();
			File file = new File(path);
			if (file.exists()) {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				headers.setContentDispositionFormData("inline", pictureFile.getFileName());
				return new org.springframework.http.ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers,
						HttpStatus.OK);
			}
		}
		return null;
	}

	@RequestMapping(value = "/user_picture_share_list")
	@ResponseBody
	public MessageModel getUserPictrureShareList(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		MessageModel model = new MessageModel(true);
		String type = request.getParameter("type");
		if ("own".equals(type)) {
			Long userId = getCurrentUserId(request.getSession());
			List<PictureShareDetailDto> pictureShareDetailDtos = pictureShareService.getDetailList(userId);
			model.setObj(pictureShareDetailDtos);
			return model;
		}
		Long userId = Long.parseLong(request.getParameter("userId"));
		if (userId != null) {
			List<PictureShareDetailDto> pictureShareDetailDtos = pictureShareService.getDetailList(userId);
			model.setObj(pictureShareDetailDtos);
		}
		return model;
	}

	@RequestMapping(value = "/readMsg")
	@ResponseBody
	public MessageModel readMsg(String id) throws IOException {
		MessageModel model = new MessageModel(true);
		pictureShareService.setRead(Long.parseLong(id));
		return model;
	}
}